package com.ry.demo.concurrent.demo.lock;

import java.util.concurrent.locks.ReentrantLock;


public class DeadLockDemo {

    ReentrantLock lock1 = new ReentrantLock();
    ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        DeadLockDemo deadLockDemo = new DeadLockDemo();
        new Thread(()->{
            try {
                deadLockDemo.methodA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                deadLockDemo.methodB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 造成methodA获得了`lock1`这把锁 休眠1秒尝试获取`lock2`这把锁
        // 造成methodB获得了`lock2`这把锁 休眠1秒尝试获取`lock1`这把锁
        // 多线程同时执行，或造成 methodA与methodB分别先获得了`lock1`与`lock2` 此时休眠1秒线程继续执行，此时锁都在对方手里

    }

    public void methodA() throws InterruptedException {
        lock1.lock();
        Thread.sleep(1000);
        lock2.lock();
    }

    public void methodB() throws InterruptedException {
        lock2.lock();
        Thread.sleep(1000);
        lock1.lock();
    }

}
